package com.money.tracker.common.utils;

import java.security.SecureRandom;

/**
 * 生成器代码 util
 *
 * @author zhangshuai
 * @date 2024/11/07
 */
public class GeneratorCodeUtil {

    private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
    private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
    private static final String NUMBER = "0123456789";
    private static final String DATA_FOR_RANDOM_CODE = CHAR_LOWER + CHAR_UPPER + NUMBER;
    private static final SecureRandom random = new SecureRandom();

    /**
     * 生成指定长度的随机字符串，包含大写字母、小写字母和数字。
     *
     * @param length 随机字符串的长度
     * @return 生成的随机字符串
     */
    public static String getRandomCode(int length) {
        if (length < 1) {
            throw new IllegalArgumentException("长度必须大于0");
        }

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int rndCharAt = random.nextInt(DATA_FOR_RANDOM_CODE.length());
            char rndChar = DATA_FOR_RANDOM_CODE.charAt(rndCharAt);
            sb.append(rndChar);
        }

        return sb.toString();
    }

}
